<template>
  <div>
    <van-nav-bar title="编辑地址" left-text="返回" left-arrow @click-left="goback"/>
    <van-address-edit
      style="background-color: #fff;"
      :areaList="areaList"
      :addressInfo="addressInfo"
      show-set-default
      show-delete
      @save="onSave"
      @delete="onDelete"
    />
  </div>
</template>

<script>
import { AddressEdit, NavBar } from 'vant';
import areaList from './area.json';
import { addressDetail, addressSave, addressDelete } from '@/api/api';
import { removeLocalStorage } from '@/utils/local-storage';

export default {
  name: 'address-edit',

  data() {
    return {
      areaList,
      addressId: 0,
      addressInfo: {
        id:0,
        name:"",
        tel:"",
        province:"",
        city:"",
        county:"",
        addressDetail:"",
        areaCode:"",
        postalCode:"",
        isDefault:false
      }
    };
  },
  created() {
    this.addressId = this.$route.query.addressId;
    if (this.addressId !== -1 && this.addressId !== 0) {
      this.init();
    }
  },

  methods: {
    init() {
      addressDetail({id: this.addressId}).then(res => {
        var temp= res.data.result;
        this.addressInfo.id=temp.id;
        this.addressInfo.name=temp.name;
        this.addressInfo.tel=temp.mobile;
        this.addressInfo.province=temp.province;
        this.addressInfo.city=temp.city;
        this.addressInfo.county=temp.region;
        this.addressInfo.areaCode=temp.areaCode;
        if(temp.isDefault==1){
          this.addressInfo.isDefault=true;
        }
        this.addressInfo.addressDetail=temp.detailAddress;
      });
    },
    onSave(content) {
      var id,isDefault=0;
      if(this.addressInfo.id!=0){
        id=this.addressInfo.id;
      }
      if(content.isDefault){
        isDefault=1;
      }
      var submitData={id:id,areaCode:content.areaCode,province:content.province,isDefault:isDefault,
        city:content.city,region:content.county,detailAddress:content.addressDetail,name:content.name,mobile:content.tel};
      addressSave(submitData).then(res => {
        this.$toast('保存成功');
        this.$router.go(-1);
      });
    },
    onDelete(content) {
      addressDelete({ id: this.addressInfo.id }).then(res => {
        this.$toast('删除成功');
        this.$router.go(-1);
      });
      removeLocalStorage('AddressId')
    },
    goback() {
      this.$router.go(-1);
    }
  },

  components: {
    [NavBar.name]: NavBar,
    [AddressEdit.name]: AddressEdit
  }
};
</script>
